package com.leo.base;

import com.leo.quartz.common.lang.ReturnCodeConstant;
import com.leo.quartz.common.request.BaseRequestParam;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liusl
 * @version 1.0
 * @date 2018/12/8 21:09
 */
public abstract class AbstractService {

    protected String buildResponseStatus() {
        return "";
    }

    protected ReturnResponse buildSuccess(){
        return new ReturnResponse(ReturnCodeConstant.SUCCESS, "");
    }

    protected  <T> Specification<T> buildSpecification(List<Predicate> predicates){
         return (Specification<T>) (root, criteriaQuery, criteriaBuilder) ->criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
    }
    protected  <T> Specification<T> buildSpecification(Map<String,Object> params, Class<T> clazz){
         return (Specification<T>) (root, criteriaQuery, criteriaBuilder) ->{
             List<Predicate> predicates = new ArrayList<>();
             params.entrySet().forEach(param-> predicates.add(criteriaBuilder.equal(root.get(param.getKey()), param.getValue())));
             return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
         };
    }

    protected <T> Specification<T> buildSpecification(BaseRequestParam param, Class<T> clazz){
        return buildSpecification(param.buildRule(), clazz);
    };
}
